package com.work.chat.custom.server.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class RestTemplateUtil {

    public RestTemplateUtil()
    {
        log.info("创建restTemplate远程请求文件");
    }

    public  <T> ResponseEntity<T> postForObject(String url, Map<String,Object> params,Map<String,String> headers, Class <T> cls)
    {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(300000);
        httpRequestFactory.setConnectTimeout(300000);
        httpRequestFactory.setReadTimeout(300000);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        if (!ObjectUtils.isEmpty(headers))
        {
            Set<Map.Entry<String, String>> entries = headers.entrySet();
            for (Map.Entry<String, String> header:entries)
            {
                requestHeaders.set(header.getKey(),header.getValue());
            }
        }
        HttpEntity<Object> httpEntity = new HttpEntity<>(params,requestHeaders);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(url, httpEntity, cls);
        return responseEntity;
    }

    public <T> T getForObject(String url, Class<T> cls) {
        HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
        httpRequestFactory.setConnectionRequestTimeout(300000);
        httpRequestFactory.setConnectTimeout(300000);
        httpRequestFactory.setReadTimeout(300000);
        RestTemplate restTemplate = new RestTemplate(httpRequestFactory);
        T t = null;
        try {
            t = restTemplate.getForObject(url, cls);
        } catch (RestClientException e) {
            e.printStackTrace();
        }
        return t;
    }
}
